<template>
	<view>
		<u-popup :show="listShow" :round="10" closeable mode="bottom" @close="$emit('update:show', false)" @open="getFamilyList">
			<view class="family">
				<view class="family-add">
					<u-button icon="plus" shape="circle" block @click="userAdd = true" text="新增常用旅客"></u-button>
				</view>
				<view class="family-list">
					<view class="family-list-item" v-for="(item, index) in userList" :key="item.Id" :name="item.Id">
						<view class="checkbox">
							<u-checkbox activeColor="#30cfda" @change="handleFamilyChecked(item)" :checked="familyChecked(item)"></u-checkbox>
						</view>
						<view class="content">
							<view>{{item.Name}}</view>
							<view>电话号: {{item.Mobile}}</view>
							<view>身份证 {{item.CardNo}}</view>
						</view>
						<view class="edit">
							<u-icon @click="handleFamilyEdit(item)" name="edit-pen" size="48rpx"></u-icon>
						</view>
					</view>
				</view>
				<view class="family-submit">
					<u-button color="#30cfda" shape="circle" block @click="handleFamilyConfirm" text="完成"></u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="userShow" :round="10"  mode="bottom" @open="familyData = [...familyList]">
			<view class="user">
				<view class="user-bar">
					<text @click="handleClose">取消</text>
					<text v-if="UserForm.Id" @click="handleFamilyDel">删除游客</text>
				</view>
				<u-form
					labelPosition="left"
					:model="UserForm"
					:rules="rules"
					ref="uForm"
					labelWidth="80"
					labelAlign="right"
					errorType="toast"
				>
					<u-form-item label="姓名" prop="Name" :borderBottom="false" >
						<u-input v-model="UserForm.Name" ></u-input>
					</u-form-item>
					<u-form-item label="电话" prop="Mobile" :borderBottom="false" >
						<u-input v-model="UserForm.Mobile" maxlength="11" ></u-input>
					</u-form-item>
					<u-form-item label="身份证号" prop="CardNo" :borderBottom="false" >
						<u-input v-model="UserForm.CardNo" maxlength="18"></u-input>
					</u-form-item>
				</u-form>
				<view class="user-submit">
					<u-button color="#30cfda" @click="handleAddSubmit" shape="circle" block>{{UserForm.Id ? '确定' : '添加'}}</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { getUsersContactsList, addUsersContacts, updateUsersContacts, deleteUsersContacts } from '@/api/mall.js'
export default {
	props: {
		show: {
			type: Boolean,
			default: false
		},
		userData: {
			type: Object,
			default: null
		},
		familyList: {	//	选中得家人项
			type: Array,
			default: []
		}
	},
	data () {
		return {
			userList: [],
			userAdd: false,
			userEdit: false,
			userActive: {},
			familyData: [],
			UserForm: {
				Name: '',
				Mobile: '',
				CardNo: ''
			},
			rules: {
				Name: {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				},
				Mobile: {
					type: 'number',
					required: true,
					message: '请填写手机号',
					trigger: ['blur', 'change']
				},
				CardNo: [
					{
						type: 'number',
						required: true,
						message: '请填写身份证',
						trigger: ['blur', 'change']
					}
				]
			}
		}
	},
	watch: {
		userAdd(data) {
			if (data) {
				this.UserForm = {
					Name: '',
					Mobile: '',
					CardNo: ''
				}
			}
			this.$emit('update:show', !data)
		}
	},
	computed: {
		userShow () {
			if (this.userData) {
				this.UserForm = {...this.userData}
			}
			return this.userData || this.userEdit || this.userAdd
		},
		listShow() {
			return this.show && !this.userShow
		}
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules)
	},
	methods: {
		// 选中回显
		familyChecked(item) {
			const UsersList = this.familyData || [];
			const userIndex = UsersList.findIndex(v => v && v.Id === item.Id);
			return userIndex !== -1;
		},
		//	 请求家人成员列表
		getFamilyList () {
			this.familyData = [...this.familyList]
			getUsersContactsList({Index: 1, Size: 100}).then(res => {
				const { ErrorCode, Data } = res || {}
				if (ErrorCode == 0) {
					this.userList = Data || []
				}
			})
		},
		//	选中人push
		handleFamilyChecked(item) {
			const UsersList = this.familyData;
			const userIndex = UsersList.findIndex(v => v && v.Id === item.Id);
			if (userIndex !== -1) {
				UsersList.splice(userIndex, 1)
				return;
			};
			UsersList.push(item);
		},
		//	选择人完成点击
		handleFamilyConfirm () {
			this.$emit('update:familyList', this.familyData)
			this.$emit('update:show', false)
		},
		// 修改信息
		handleFamilyEdit(item) {
			this.userEdit = true
			this.UserForm = {...item}
		},
		handleClose() {
			
			if (!this.userAdd && !this.userEdit) {
				this.$emit('userClose', true)
				return;
			}
			this.userEdit && (this.userEdit = false)
			this.userAdd && (this.userAdd = false)	
		},
		//	确认添加
		handleAddSubmit() {
			this.$refs.uForm.validate().then(validate => {
				const { Id, CardNo, Mobile } = this.UserForm || {} 
				const regMobile = /^1\d{10}$/
				if (!this.realIDcard(CardNo)) return;
				if (!regMobile.test(Mobile)) {
					uni.showToast({
						title: '请输入正确的电话',
						icon: 'none'
					})
					return;
				}
				let request = addUsersContacts
				if (Id) {
					request = updateUsersContacts
				}
				request({
					...this.UserForm,
					Relation: 4
				}).then(res => {
					uni.showToast({
						title: Id ? '修改成功' : '添加成功',
						icon: 'none'
					});
					setTimeout(() => {
						if (Id) {
							const userIndex = this.familyData.findIndex(v => v && v.Id === Id);
							if (userIndex !== -1) {
								this.familyData.splice(userIndex, 1, this.UserForm)
								this.$emit('userClose');
							};
						}
						this.handleFamilyConfirm()
					}, 500)
				})
			}).catch(errors => {
				
			})
		},
		handleFamilyDel() {
			const { Id } = this.UserForm || {}
			uni.showModal({
				title: '您确定要删除该购票人吗？',
				success: (res) => {
					if (res.confirm) {
						deleteUsersContacts({Id}).then(resp => {
							this.handleFamilyChecked(this.UserForm)
							uni.showToast({
								title: '删除成功',
								icon: 'none',
								success: () => {
									this.$emit('userClose');
									setTimeout(() => this.handleFamilyConfirm(), 500)
								}
							});
							
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				},
			})
		},
		realIDcard(idcard) {
			let regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/ //身份证验证
			if (regIdCard.test(idcard)) {
				if (idcard.length == 18) {
					var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
					var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
					var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
					for (var i = 0; i < 17; i++) {
						idCardWiSum += idcard.substring(i, i + 1) * idCardWi[i];
					}
					var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
					var idCardLast = idcard.substring(17); //得到最后一位身份证号码
					//如果等于2，则说明校验码是10，身份证号码最后一位应该是X
					if (idCardMod == 2) {
						if (idCardLast == "X" || idCardLast == "x") {
						} else {
							uni.showToast({
								title: '身份证号码错误！',
								icon: 'none'
							})
							return false;
						}
					} else {
						//用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
						if (idCardLast == idCardY[idCardMod]) {
						} else {
							uni.showToast({
								title: '身份证号码错误！',
								icon: 'none'
							})
							return false;
						}
					}
				}
			} else {
				uni.showToast({
					title: '身份证号码格式错误！',
					icon: 'none'
				})
				return false;
			}
			return true
		}
	}
}
</script>

<style lang="scss" scoped>
.family{
	max-height: 80vh;
	&-add{
		width: 100%;
		padding: 80rpx 60rpx 20rpx;
	}
	&-list{
		padding: 0 40rpx;
		max-height: calc(100% - 380rpx);
		overflow-y: scroll;
		&-item{
			padding: 20rpx 0;
			border-bottom: 1px solid #e6ebf1;
			display: flex;
			&:last-child{
				border-bottom: 0;
			}
			.checkbox{
				width: 100rpx;
				height: 120rpx;
				padding: 30rpx;
			}
			.content{
				margin-left: 10rpx;
				width: calc(100% - 220rpx);
				height: 120rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				view{
					color: #333;
					font-size: 26rpx;
				}
			}
			.edit{
				padding: 30rpx;
				margin-left: 10rpx;
				width: 100rpx;
				height: 120rpx;
			}
		}
	}
	&-submit{
		padding-top: 20rpx;
		background: #fff;
	}
}
.user{
	padding: 20rpx;
	&-bar{
		width: 100%;
		line-height: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: space-between;
		>text{
			color: #333;
			font-size: 30rpx;
			&:last-child{
				color: #30cfda;
			}
		}
	}
	&-submit{
		padding-top: 20rpx;
		background: #fff;
	}
}
</style>